﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectDirector.Domain.Abstracts;
using ProjectDirector.ViewModels;
using ProjectDirector.Domain.Entities;
using System.Web.Security;
using ProjectDirector.Domain.Concretes;

namespace ProjectDirector.Controllers
{
    public class CustomerController : Controller
    {
        private IProjectDirectorRepository repository = null;
        public CustomerController(IProjectDirectorRepository _repository)
        {
            this.repository = _repository;
        }
        //
        // GET: /Customer/
        [Authorize(Roles="administrator")]
        public ActionResult Index()
        {
            var model = new CustomerViewModel()
            {
                Customers = ( from c in repository.GetCustomers()
                              where !c.IsDeleted.HasValue
                                  select c).ToList(),
                Address = new Domain.Entities.Address(),
                Countries = repository.GetCountries(),
                BusinessTypes = repository.GetBusinessTypes()
            };             
            return View(model);
        }

        //
        // GET: /Customer/Details/5
         [Authorize(Roles = "administrator")]
        public ActionResult Details(int id)
        {
            try
            {
                Customer _customer = repository.GetCustomers().SingleOrDefault(x => x.CustomerId == id);
                var _model = new CustomerViewModel
                {
                    Customer = _customer,
                    Address = repository.GetAddress().SingleOrDefault(x => x.AddressId == _customer.AddressId),
                    CreatedByName = GetAuditTrail(_customer.CreatedBy),
                    UpdatedByName = GetAuditTrail(_customer.UpdatedBy.HasValue ? _customer.UpdatedBy.Value : Guid.Empty)
                };
                return View(_model);
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            return View("Index");

        }

        //
        // GET: /Customer/Create
         [Authorize(Roles = "administrator")]
        public ActionResult Create()
        {
            var model = FillCustomerViewModel();
            return View(model);
        }

        private CustomerViewModel FillCustomerViewModel()
        {
            var model = new CustomerViewModel
            {
                Address = new Domain.Entities.Address(),
                BusinessTypes = repository.GetBusinessTypes(),
                Countries = repository.GetCountries(),
                Customer = new Domain.Entities.Customer()
            };
            return model;
        } 

        //
        // POST: /Customer/Create

        [HttpPost]
        [Authorize(Roles = "administrator")]
        public ActionResult Create(CustomerViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Customer
                    Customer _customer = new Customer();
                    _customer.CompanyName = model.Customer.CompanyName;
                    _customer.BusinessTypeId = model.Customer.BusinessTypeId;
                    _customer.Telephone = model.Customer.Telephone;
                    _customer.Email = (string.IsNullOrEmpty(model.Customer.Email) ? "N/A" : model.Customer.Email);
                    _customer.FaxNumber = (string.IsNullOrEmpty(model.Customer.FaxNumber) ? "N/A" : model.Customer.FaxNumber);
                    _customer.WebSite = (string.IsNullOrEmpty(model.Customer.WebSite) ? "N/A" : model.Customer.WebSite);
                    _customer.CreatedBy = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
                    _customer.DateCreated = DateTime.Now;

                    //Address
                    Address _address = new Address();
                    _address.Address1 = model.Address.Address1;
                    _address.Address2 = model.Address.Address2;
                    _address.Town = model.Address.Town;
                    _address.PostalCode = model.Address.PostalCode;
                    _address.CountryId = model.Address.CountryId;

                    var _model = FillCustomerViewModel();
                    //Add new client and address
                    if (repository.AddCustomer(_customer, _address) > 0)
                    {
                        _model.Result = "New Client details has been created successfully.";
                        return View(_model);
                    }
                }
                else
                {
                }
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }           
            return View(FillCustomerViewModel());
        }
       
        //
        // GET: /Customer/Edit/5
         [Authorize(Roles = "administrator")]
        public ActionResult Edit(int id)
        {
            try
            {
                var _model = FillCustomerViewModel();
                Customer _customer = repository.GetCustomers().SingleOrDefault(x => x.CustomerId == id);           

                _model.Customer = _customer;
                _model.Address = repository.GetAddress().SingleOrDefault(x => x.AddressId == _customer.AddressId);
                _model.CreatedByName = GetAuditTrail(_customer.CreatedBy);
                _model.UpdatedByName = GetAuditTrail(_customer.UpdatedBy.HasValue ? _customer.UpdatedBy.Value : Guid.Empty);
                
                return View(_model);
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            return View(FillCustomerViewModel());
        }

        //
        // POST: /Customer/Edit/5

        [HttpPost]
        [Authorize(Roles = "administrator")]
        public ActionResult Edit(int id, CustomerViewModel _model)
        {
            try
            {
                Customer _customer = _model.Customer;
                _customer.UpdatedBy = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
                _customer.DateUpdated = DateTime.Now;

                Address _address = _model.Address;
                if (repository.UpdateCustomer(_customer, _address) > 0)
                {
                    var _cvmodel = FillCustomerViewModel();
                    _cvmodel.Result = "Customer details has been updated.";
                    return View(_cvmodel);
                }
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            return View(FillCustomerViewModel());         
        }

        //
        // GET: /Customer/Delete/5 
        [Authorize(Roles = "administrator")]
        public ActionResult Delete(int id)
        {
            var _customer = repository.GetCustomers().SingleOrDefault(x => x.CustomerId == id);
            return View(_customer);
        }

        //
        // POST: /Customer/Delete/5
        [HttpPost]
        [Authorize(Roles = "administrator")]
        public ActionResult Delete(int id, Customer customer)
        {
            try
            {
                Customer _customer = new Customer();
                _customer.CustomerId = customer.CustomerId;
                _customer.IsDeleted = true;
                _customer.UpdatedBy = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
                _customer.DateUpdated = DateTime.Now;
                if (repository.DeleteCustomer(_customer) > 0)  {
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            return View();
        }

        private string GetAuditTrail(Guid id)
        {
            string name = string.Empty;
            try
            {
                var getName = (from e in repository.GetEmployees()
                               where e.UserId == id
                               select new { Name = e.FirstName + " " + e.LastName }).SingleOrDefault();
                if (getName != null)
                    name = getName.Name;
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            return name;
        }
    }
}
